#!/bin/sh

# code inspired by the app "Mobile HotSpot"

SSID="ipv6"
# KEY is a WEP key, and must be a 10 digit hexidecimal number with optional -'s
KEY="abcd-ef01-23"
# INTERFACE is either wlan0 (wifi) or usb0 (usb networking)
INTERFACE="usb0"
# NETWORK is the first three octets of a ipv4 local address.  This network only
# used for DHCP/DNS
NETWORK="10.255.255"

PREFIX=`/sbin/ip -6 addr show scope global | awk '/inet6/ { print $2}'| head -1 |sed s@/.*@@`

if [ -z "$PREFIX" ]; then
  echo no ipv6 connection detected
  exit 1
fi

if [ -z "$1" ]; then
  echo 'this script takes one argument: "start" or "stop"'
  exit 1
fi

if [ "$1" == "start" ]; then

  # disable nat64 on startup
  if [ -f /etc/nat64.conf ]; then
    mv /etc/nat64.conf /etc/nat64.conf.temp-disabled
    UNDO_TEMP_DISABLE=1
  fi

  ifconfig $INTERFACE up

  if [ "$INTERFACE" = "wlan0" ]; then
    iwconfig $INTERFACE mode ad-hoc
    iwconfig $INTERFACE essid "$SSID"
    iwconfig $INTERFACE key "$KEY" restricted
  fi

  ifconfig $INTERFACE $NETWORK.1 netmask 255.255.255.0
  ip addr add $PREFIX/64 dev $INTERFACE

  /usr/sbin/dnsmasq -i $INTERFACE \
        -a $NETWORK.1 \
        -I lo -z -x /var/run/dnsmasq.$INTERFACE.pid \
	--dhcp-range=$NETWORK.10,$NETWORK.100,6h \
	--dhcp-option=3,$NETWORK.1 \
	--dhcp-option=6,$NETWORK.1

  echo 1 >/proc/sys/net/ipv6/conf/all/forwarding

  cat <<EOF >/etc/radvd.conf.$INTERFACE
interface $INTERFACE {
  MinRtrAdvInterval 3;
  MaxRtrAdvInterval 10;
  AdvLinkMTU 1400;
  AdvSendAdvert on;
  prefix $PREFIX/64
  {
    AdvOnLink on;
    AdvAutonomous on;
    AdvValidLifetime 300;
    AdvPreferredLifetime 120;
  };
};
EOF

  /usr/sbin/radvd -C /etc/radvd.conf.$INTERFACE -p /var/run/radvd.pid

  if [ -n "$UNDO_TEMP_DISABLE" ]; then
    mv /etc/nat64.conf.temp-disabled /etc/nat64.conf
  fi
elif [ "$1" == "stop" ]; then
  kill `cat /var/run/radvd.pid /var/run/dnsmasq.$INTERFACE.pid`
  ifconfig $INTERFACE down
  echo 0 >/proc/sys/net/ipv6/conf/all/forwarding
else
  echo unknown argument: $1
  exit 1
fi
